package com.feiyu.other;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;

import java.io.File;
import java.io.IOException;

/**
 * 获取相片元信息
 *
 * @author nanshouxiao@teacher.com.cn
 * @date 2017-11-02 14:10
 */
public class ImageMetadata {
    public static void main(String[] args) throws Exception {
        String filePath = "C:\\Users\\awei\\Documents\\20171102164944.jpg";
        getImageMetadata(filePath);
    }
    private static void getImageMetadata(String imagePath) throws ImageProcessingException, IOException {
        File file = new File(imagePath);
        if (!file.exists()) {
            return;
        }
        Metadata metadata = ImageMetadataReader.readMetadata(file);

        for (Directory directory : metadata.getDirectories()) {
            for (Tag tag : directory.getTags()) {
                System.out.format("[%s] - %s = %s",
                        directory.getName(), tag.getTagName(), tag.getDescription());
                System.out.println();
            }
            if (directory.hasErrors()) {
                for (String error : directory.getErrors()) {
                    System.err.format("ERROR: %s", error);
                }
            }
        }
    }

    private static void printDirectory(String imagePath) throws Exception {
        File file = new File(imagePath);
        if (!file.exists()) {
            return;
        }
        Metadata metadata = ImageMetadataReader.readMetadata(file);

        for (Directory directory : metadata.getDirectories()) {
            System.out.println(directory);
        }
    }
}
